package com.interview.config;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.SetBucketLoggingRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.interview.properties.AliyunOSSProperties;

/**
 * @author zzw
 * @date 2025/6/15
 * @description 阿里云OSS配置文件
 */
@Slf4j
@Configuration
public class AliyunOSSAutoConfig {

    @Autowired
    private AliyunOSSProperties aliyunOSSProperties;

    @Bean
    public OSS ossClient() {
        log.info("-----------------开始创建OSSClient--------------------");
        OSS ossClient = new OSSClientBuilder().build(
                aliyunOSSProperties.getEndpoint(),
                aliyunOSSProperties.getAccessKeyId(),
                aliyunOSSProperties.getAccessKeySecret()
                                                    );

        //判断容器是否存在,不存在就创建
        if (!ossClient.doesBucketExist(aliyunOSSProperties.getBucketName())) {
            ossClient.createBucket(aliyunOSSProperties.getBucketName());
            CreateBucketRequest createBucketRequest = new CreateBucketRequest(aliyunOSSProperties.getBucketName());
            //设置问公共可读
            createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
            ossClient.createBucket(createBucketRequest);
        }

        //添加客户端访问日志
        SetBucketLoggingRequest request = new SetBucketLoggingRequest(aliyunOSSProperties.getBucketName());
        // 设置存放日志文件的存储空间。
        request.setTargetBucket(aliyunOSSProperties.getBucketName());
        // 设置日志文件存放的目录。
        request.setTargetPrefix(aliyunOSSProperties.getBucketName());
        ossClient.setBucketLogging(request);

        log.info("-----------------结束创建OSSClient--------------------");
        return ossClient;
    }
}
